package com.yulp.springboot2task.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.Ordered;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Optional;

/**
 * @description:
 * @date: 2019/11/6 14:15.
 * @author: yulipeng.
 */

@Component
@Lazy(false)
public class SpringContext implements ApplicationContextAware, ApplicationListener, Ordered {
    private static ApplicationContext act;

    public SpringContext() {
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        act = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return act;
    }

    public static Object getBean(String beanName) {
        return act.getBean(beanName);
    }

    public static <T> T getBean(String beanName, Class<T> tClass) {
        return act.getBean(beanName, tClass);
    }

    public static <T> Map<String, T> getBean(Class<T> tClass) {
        return act.getBeansOfType(tClass);
    }

    /**
     * 如果有多个Bean符合Class, 取出第一个.
     * @param beanClass
     * @param <T>
     * @return
     */
    public static <T> T getBeanByClass(Class<T> beanClass) {
        Map<String, T> bean = getBean(beanClass);
        if (bean != null && !bean.isEmpty()) {
            return bean.values().iterator().next();
        } else {
            return null;
        }
    }

    public static Resource getResource(String resourceName) {
        return act.getResource(resourceName);
    }

    public static String getProperty(String key) {
        return act.getEnvironment().getProperty(key);
    }

    public static String getProperty(String key, String defaultValue) {
        return Optional.ofNullable(act.getEnvironment().getProperty(key)).orElse(defaultValue);
    }

    @Override
    public int getOrder() {
        return -2147483648;
    }


    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        // 此处监听的是 ApplicationEvent
        // 使用场景：在实际项目中，我们通常希望web应用程序启动（这里指spring IOC容器加载bean）成功后，进行初始化工作，
        // 比如：数据库的加载、特定任务的检查等。
    }
}
